<?php
namespace Common\Model;
use Think\Model;
class FriendModel extends Model {
	protected $connection = 'DB_BASE_DSN';
	protected $tableName = 'qyx_friend'; 
	
	public function getFriendList($data){
		$map = array();
		
		if(!empty($data['custid'])){
			$map['custid'] = $data['custid'];
		}
		
		if(!empty($data['tcustid']) && is_array($data['tcustid'])){
			$map['tcustid'] = array('in' , $data['tcustid']);
		}
		
		$total = $this->where($map)->count();
		
		$fields = array('id','tcustid as custid','nickname','msgsetting','status','createtime','updatetime');
		
		if(empty($data['sortField']))$data['sortField'] = "id";
		if(empty($data['sortOrder']))$data['sortOrder'] = "desc";
		
		if(empty($data['pageSize']) && empty($data['pageIndex']))
			$result = $this->field($fields)->where($map)->order("{$data['sortField']} {$data['sortOrder']}")->select();
		else 
			$result = $this->field($fields)->where($map)->order("{$data['sortField']} {$data['sortOrder']}")->limit($data['pageIndex']*$data['pageSize'] , $data['pageSize'])->select();
		
		$pages = !empty($data['pageSize']) ? ceil($total/$data['pageSize']) : 1;
		
		return array('total'=>$total , 'data'=>$result , 'pages'=>$pages);
	}
	
	
	public function getFriendIdsByCustId($custid){
		$map['custid'] = $custid;
		$map['status'] = 1;
		$result = $this->field('tcustid,msgsetting')->where($map)->select();
		return $result;
	}
	
	public function getDistinctCustId(){
		$result = $this->distinct(true)->field('custid')->select();
		return $result;
	}
	
	public function getFriend($data){
		$map['custid'] = $data['custid'];
		$map['tcustid'] = $data['tcustid'];
		$result = $this->where($map)->find();
		return $result;
	}
	
	
	public function getFriendById($id){
		$map['id'] = $id;
		$fields = array('id','custid as _custid','tcustid as custid','msgsetting','status','createtime','updatetime');
		$result = $this->field($fields)->where($map)->find();
		return $result;
	}
	
	
	public function addFriend($data){
		$map['custid'] = $data['custid'];
		$map['tcustid'] = $data['tcustid'];
		$ret = $this->where($map)->find();
		if(!empty($ret)){
			return $ret['id'];
		}else{
			$result = $this->add($data);
			return $result;
		}
	}
	
	public function updateFriend($data){
		$map['custid'] = $data['custid'];
		$map['tcustid'] = $data['tcustid'];
		$data['updatetime'] = date("Y-m-d H:i:s");
		$result = $this->where($map)->save($data);
		return $result;
	}
	
	public function updateFriendById($data){
		$map['id'] = $data['id'];
		$data['updatetime'] = date("Y-m-d H:i:s");
		$result = $this->where($map)->save($data);
		return $result;
	}
	
	public function deleteFriend($data){
		$map['custid'] = $data['custid'];
		$map['tcustid'] = $data['tcustid'];
		$result = $this->where($map)->delete();
		return $result;
	}
	
}


